package net.adst.ui.other;

import com.toedter.calendar.JDateChooser;
import net.adst.beans.OurTecInf;
import net.adst.resources.Constants;
import net.adst.resources.VariableNames;
import net.adst.searcher.Searcher;
import net.adst.util.DataManager;
import net.adst.util.GBC;
import net.adst.util.MainDataBuilder;
import net.adst.util.MyUtils;
import org.apache.poi.hssf.extractor.ExcelExtractor;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import sun.net.ResourceManager;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.TreeSet;

/**
 * Created with IntelliJ IDEA.
 * User: alekseipot
 * Date: 22.12.12
 * Time: 2:30
 * To change this template use File | Settings | File Templates.
 */
public class AddOurPanel extends JPanel {
    private Dimension labelDimension = new Dimension(110, 20);
    private Dimension fieldDimension = new Dimension(165, 20);
    private ArrayList<OurTecInf> tecInf;
    private JButton addButton;
    private JButton saveButton;
    private JButton clearButton;
    private JButton removeButton;
    private JTable addingTable;
    private JDateChooser dateFrom;
    private JDateChooser dateTo;
    private DefaultTableModel model;
    private JTextField chInField;
    private JTextField chOutField;
    private JComboBox tecNameCombo;
    private JComboBox surnameCombo;
    private JComboBox kindOfPaymentCombo;
    private JComboBox customerCombo;
    private JComboBox objectCombo;
    private JTextField priceField;
    private OurTecInf tec = new OurTecInf("", "", "", "", "");

    public AddOurPanel() {
        addElements();
        addTable();
        addLogic();
        setBackground(Constants.COLOR_LIGHT_BLUE);
    }

    public void addElements() {
        tecInf = (ArrayList<OurTecInf>) DataManager.getObject(VariableNames.TEC_OUR_INFO);
        setLayout(new GridBagLayout());
        JLabel dateFromLabel = new JLabel("день с:");
        JLabel dateToLabel = new JLabel("день по:");
        dateFrom = new JDateChooser();
        Calendar dtFrom = Calendar.getInstance(), dtTo = Calendar.getInstance();
        dtFrom.set(Calendar.DAY_OF_WEEK, dtFrom.getFirstDayOfWeek());
        dateTo = new JDateChooser();
        dateFrom.setDate(dtFrom.getTime());
        dateTo.setDate(dtTo.getTime());
        dateFrom.setMaximumSize(fieldDimension);
        dateFrom.setPreferredSize(fieldDimension);
        dateFrom.setMinimumSize(fieldDimension);
        dateTo.setMaximumSize(fieldDimension);
        dateTo.setPreferredSize(fieldDimension);
        dateTo.setMinimumSize(fieldDimension);


        JLabel chInLabel = new JLabel("счет входищий:");
//        chInLabel.setMaximumSize(labelDimension);
//        chInLabel.setPreferredSize(labelDimension);
//        chInLabel.setMinimumSize(labelDimension);
        chInField = new JTextField();
        chInField.setMaximumSize(fieldDimension);
        chInField.setPreferredSize(fieldDimension);
        chInField.setMinimumSize(fieldDimension);

        JLabel chOutLabel = new JLabel("счет исходящий:");
//        chOutLabel.setMaximumSize(labelDimension);
//        chOutLabel.setPreferredSize(labelDimension);
//        chOutLabel.setMinimumSize(labelDimension);
        chOutField = new JTextField();
        chOutField.setMaximumSize(fieldDimension);
        chOutField.setPreferredSize(fieldDimension);
        chOutField.setMinimumSize(fieldDimension);


        JLabel tecNameLabel = new JLabel("именование техники:");
//        tecNameLabel.setMaximumSize(labelDimension);
//        tecNameLabel.setPreferredSize(labelDimension);
//        tecNameLabel.setMinimumSize(labelDimension);
        tecNameCombo = new JComboBox();
        DefaultComboBoxModel tecNameModel = new DefaultComboBoxModel();
        for (OurTecInf item : tecInf) {
            tecNameModel.addElement(item.getFullName());
        }
        tecNameCombo.setModel(tecNameModel);
        tecNameCombo.setEditable(false);
        tecNameCombo.setMaximumSize(new Dimension(235, 20));
        tecNameCombo.setPreferredSize(new Dimension(235, 20));
        tecNameCombo.setMinimumSize(new Dimension(235, 20));

        if (tecNameCombo.getSelectedItem() != null) {
            for (OurTecInf item : tecInf) {
                if (item.getFullName().equals(tecNameCombo.getSelectedItem().toString())) {
                    tec = new OurTecInf(item.getFullName(), item.getShortName(), item.getCostHour(), item.getRashod(), item.getSalary());
                }
            }
        }
        JLabel surnameLabel = new JLabel("фамилия:");
//        surnameLabel.setMaximumSize(labelDimension);
//        surnameLabel.setPreferredSize(labelDimension);
//        surnameLabel.setMinimumSize(labelDimension);
        surnameCombo = new JComboBox();
        ArrayList<String> surnameList = (ArrayList<String>) DataManager.getObject(VariableNames.OUR_SURNAME_LIST);
        DefaultComboBoxModel surnameModel = new DefaultComboBoxModel();
        for (String item : surnameList) {
            surnameModel.addElement(item);
        }
        surnameCombo.setModel(surnameModel);
        surnameCombo.setEditable(true);
        surnameCombo.setMaximumSize(fieldDimension);
        surnameCombo.setPreferredSize(fieldDimension);
        surnameCombo.setMinimumSize(fieldDimension);


        JLabel kindOfPaymentLabel = new JLabel("вид оплаты:");
//        kindOfPaymentLabel.setMaximumSize(labelDimension);
//        kindOfPaymentLabel.setPreferredSize(labelDimension);
//        kindOfPaymentLabel.setMinimumSize(labelDimension);
        kindOfPaymentCombo = new JComboBox();
        DefaultComboBoxModel kindOfPaymentModel = new DefaultComboBoxModel();
        kindOfPaymentModel.addElement("без наличный");
        kindOfPaymentModel.addElement("наличный");
        kindOfPaymentCombo.setModel(kindOfPaymentModel);
        kindOfPaymentCombo.setEditable(true);
        kindOfPaymentCombo.setMaximumSize(fieldDimension);
        kindOfPaymentCombo.setPreferredSize(fieldDimension);
        kindOfPaymentCombo.setMinimumSize(fieldDimension);


        JLabel customerLabel = new JLabel("заказчик:");
//        customerLabel.setMaximumSize(labelDimension);
//        customerLabel.setPreferredSize(labelDimension);
//        customerLabel.setMinimumSize(labelDimension);
        customerCombo = new JComboBox();
        TreeSet<String> customerList = (TreeSet<String>) DataManager.getObject(VariableNames.TEC_OUR_CUSTOMER_LIST);
        DefaultComboBoxModel customerModel = new DefaultComboBoxModel();
        for (String item : customerList) {
            customerModel.addElement(item);
        }
        customerCombo.setModel(customerModel);
        customerCombo.setEditable(true);
        customerCombo.setMaximumSize(fieldDimension);
        customerCombo.setPreferredSize(fieldDimension);
        customerCombo.setMinimumSize(fieldDimension);


        JLabel objectNameLabel = new JLabel("объект:");
//        objectNameLabel.setMaximumSize(labelDimension);
//        objectNameLabel.setPreferredSize(labelDimension);
//        objectNameLabel.setMinimumSize(labelDimension);
        objectCombo = new JComboBox();
        TreeSet<String> objectList = (TreeSet<String>) DataManager.getObject(VariableNames.TEC_OUR_OBJECT_LIST);
        DefaultComboBoxModel objectModel = new DefaultComboBoxModel();
        for (String item : objectList) {
            objectModel.addElement(item);
        }
        objectCombo.setModel(objectModel);
        objectCombo.setEditable(true);
        objectCombo.setMaximumSize(fieldDimension);
        objectCombo.setPreferredSize(fieldDimension);
        objectCombo.setMinimumSize(fieldDimension);

        JLabel priceLabel = new JLabel("цена за час:");
        priceField = new JTextField();
        priceField.setText(tec.getCostHour());
        priceField.setMaximumSize(fieldDimension);
        priceField.setPreferredSize(fieldDimension);
        priceField.setMinimumSize(fieldDimension);

        addButton = new JButton("добавить");
        saveButton = new JButton(new ImageIcon(ResourceManager.class.getResource("/images/save.png")));
        clearButton = new JButton("удалить все записи.");
        clearButton.setFocusPainted(false);

        removeButton = new JButton(new ImageIcon(ResourceManager.class.getResource("/images/remove.png")));
        removeButton.setEnabled(false);
        removeButton.setFocusPainted(false);
        removeButton.setToolTipText("Удалить запись(си) из таблицы.");

        add(dateFromLabel, new GBC(0, 0).setInsets(4, 4).setAnchor(GBC.WEST));
        add(dateFrom, new GBC(1, 0).setInsets(4, 4).setAnchor(GBC.WEST));
        add(dateToLabel, new GBC(0, 1).setInsets(4, 4).setAnchor(GBC.WEST));
        add(dateTo, new GBC(1, 1).setInsets(4, 4).setAnchor(GBC.WEST));

        add(chInLabel, new GBC(0, 2).setInsets(8, 4).setAnchor(GBC.WEST));
        add(chInField, new GBC(1, 2).setInsets(4, 4).setAnchor(GBC.WEST));
        add(chOutLabel, new GBC(0, 3).setInsets(8, 4).setAnchor(GBC.WEST));
        add(chOutField, new GBC(1, 3).setInsets(4, 4).setAnchor(GBC.WEST));

        add(tecNameLabel, new GBC(4, 0).setInsets(4, 4).setAnchor(GBC.WEST));
        add(tecNameCombo, new GBC(5, 0, 4, 1).setInsets(4, 4).setAnchor(GBC.WEST));
        add(surnameLabel, new GBC(4, 1).setInsets(4, 4).setAnchor(GBC.WEST));
        add(surnameCombo, new GBC(5, 1).setInsets(4, 4).setAnchor(GBC.WEST));

        add(kindOfPaymentLabel, new GBC(4, 2).setInsets(8, 4).setAnchor(GBC.WEST));
        add(kindOfPaymentCombo, new GBC(5, 2).setInsets(4, 4).setAnchor(GBC.WEST));
        add(customerLabel, new GBC(4, 3).setInsets(8, 4).setAnchor(GBC.WEST));
        add(customerCombo, new GBC(5, 3).setInsets(4, 4).setAnchor(GBC.WEST));

        add(objectNameLabel, new GBC(8, 1, 1, 1).setInsets(4, 8).setAnchor(GBC.WEST));
        add(objectCombo, new GBC(9, 1, 1, 1).setInsets(4, 4).setAnchor(GBC.WEST));

        add(priceLabel, new GBC(8, 2, 1, 1).setInsets(4, 8).setAnchor(GBC.WEST));
        add(priceField, new GBC(9, 2, 1, 1).setInsets(4, 4).setAnchor(GBC.WEST));

        add(addButton, new GBC(10, 0).setInsets(4, 4));
        add(saveButton, new GBC(10, 1, 1, 1).setInsets(4, 4));
        add(clearButton, new GBC(9, 3).setInsets(4, 4));
        add(removeButton, new GBC(10, 2, 1, 2).setInsets(4, 4));
    }

    private void addTable() {
        model = new DefaultTableModel( //NotEditableDefaultTableModel
                new Object[][]{
                },
                Constants.OUR_НEADER
        ) {
            @Override
            public boolean isCellEditable(final int row, final int col) {
                if (col == 0 || col == 1 || col == 12 || col == 13 || col == 14 || col == 8 || col == 17)
                    return false;
                return true;
            }
        };
        addingTable = new JTable(model);
        addingTable.setRowHeight(Constants.TABLE_ROW_HEIGHT);
        addingTable.getTableHeader().setReorderingAllowed(false);
        setWidth(addingTable);
        addingTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

        JScrollPane scrollPane = new JScrollPane(addingTable);
        scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);

        add(scrollPane, new GBC(0, 4, 11, 1).setFill(GBC.BOTH).setWeight(1, 1));

    }

    private void addLogic() {
        addingTable.addPropertyChangeListener(new PropertyChangeListener() {
            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                if (evt.getPropertyName().equals("tableCellEditor") && evt.getNewValue() != null) {
                    saveButton.setEnabled(false);
                }
                if (evt.getPropertyName().equals("tableCellEditor") && evt.getNewValue() == null) {
                    saveButton.setEnabled(true);
                }
            }
        });

        addingTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                ListSelectionModel lsm = (ListSelectionModel) e.getSource();
                if (lsm.isSelectionEmpty()) {
                    removeButton.setEnabled(false);
                } else {
                    removeButton.setEnabled(true);
                }
            }
        });

        model.addTableModelListener(new TableModelListener() {
            @Override
            public void tableChanged(TableModelEvent e) {
                int row = e.getFirstRow();

                if (e.getColumn() == 5 && !addingTable.getValueAt(row, 5).toString().isEmpty()) {
                    try {
                        addingTable.setValueAt(Double.valueOf(addingTable.getValueAt(row, 5).toString()) * Double.valueOf(tec.getRashod()), row, 12);
                        addingTable.setValueAt(Double.valueOf(addingTable.getValueAt(row, 12).toString()) * Double.valueOf(DataManager.getObject(VariableNames.TOPLIVO_COST).toString()), row, 13);
                        addingTable.setValueAt(Double.valueOf(addingTable.getValueAt(row, 5).toString()) * Double.valueOf(tec.getSalary()), row, 14);
                    } catch (IllegalArgumentException ex) {
                        addingTable.setValueAt("", row, 5);
                    }
                }
                if ((e.getColumn() == 6 && !addingTable.getValueAt(row, 6).toString().isEmpty()) || ((e.getColumn() == 7 && !addingTable.getValueAt(row, 7).toString().isEmpty()))) {
                    try {
                        addingTable.setValueAt(Double.valueOf(addingTable.getValueAt(row, 6).toString()) * Double.valueOf(addingTable.getValueAt(row, 7).toString()), row, 8);
                    } catch (IllegalArgumentException ex) {
                        addingTable.setValueAt("", row, 6);
                    }
                }
                if (e.getColumn() == 5 || e.getColumn() == 6 || e.getColumn() == 7 || e.getColumn() == 15 || e.getColumn() == 18 || e.getColumn() == 19) {
                    Double pribl = !addingTable.getValueAt(row, 8).toString().isEmpty() ? Double.valueOf(Double.valueOf(addingTable.getValueAt(row, 8).toString())) : new Double("0");
                    Double dtRub = !addingTable.getValueAt(row, 13).toString().isEmpty() ? Double.valueOf(Double.valueOf(addingTable.getValueAt(row, 13).toString())) : new Double("0");
                    Double salary = !addingTable.getValueAt(row, 14).toString().isEmpty() ? Double.valueOf(Double.valueOf(addingTable.getValueAt(row, 14).toString())) : new Double("0");
                    Double dop = new Double("0");
                    Double arenda = new Double("0");
                    Double prorab = new Double("0");
                    try {
                        dop = !addingTable.getValueAt(row, 15).toString().isEmpty() ? Double.valueOf(Double.valueOf(addingTable.getValueAt(row, 15).toString())) : new Double("0");
                    } catch (IllegalArgumentException ex) {
                        addingTable.setValueAt("", row, 15);
                    }
                    try {
                        arenda = !addingTable.getValueAt(row, 18).toString().isEmpty() ? Double.valueOf(Double.valueOf(addingTable.getValueAt(row, 18).toString())) : new Double("0");
                    } catch (IllegalArgumentException ex) {
                        addingTable.setValueAt("", row, 18);
                    }
                    try {
                        prorab = !addingTable.getValueAt(row, 19).toString().isEmpty() ? Double.valueOf(Double.valueOf(addingTable.getValueAt(row, 19).toString())) : new Double("0");
                    } catch (IllegalArgumentException ex) {
                        addingTable.setValueAt("", row, 19);
                    }
                    addingTable.setValueAt(pribl - dtRub - salary - dop - arenda - prorab, row, 17);
                }

            }
        }

        );

        tecNameCombo.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                for (OurTecInf item : tecInf) {
                    if (item.getFullName().equals(tecNameCombo.getSelectedItem().toString())) {
                        tec = new OurTecInf(item.getFullName(), item.getShortName(), item.getCostHour(), item.getRashod(), item.getSalary());
                        break;
                    }
                }
                priceField.setText(tec.getCostHour());
                tecNameCombo.setToolTipText(tecNameCombo.getSelectedItem().toString());

            }
        });

        clearButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                cleanTable();
            }
        });
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                saveButton.setEnabled(true);
                Date dtFrom = dateFrom.getCalendar().getTime();
                Date dtTo = dateTo.getCalendar().getTime();
                while (MyUtils.compareDate(dtTo, dtFrom)) {
                    model.addRow(new Object[]{(new SimpleDateFormat("dd.MM.yyyy")).format(dtFrom.getTime()), tecNameCombo.getSelectedItem(), chInField.getText(), chOutField.getText(), surnameCombo.getSelectedItem(), "", "", tec.getCostHour(), "", kindOfPaymentCombo.getSelectedItem(), customerCombo.getSelectedItem(), objectCombo.getSelectedItem(), "", "", "", "", "", "", "", "", ""});
                    dtFrom.setTime(dtFrom.getTime() + 24 * 60 * 60 * 1000);
                }
            }
        });

        removeButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int response = JOptionPane.showOptionDialog(null, "Вы, действительно хотите удалить запись(си)?", "Удалить?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null);
                if (response == JOptionPane.YES_OPTION) {
                    while (addingTable.getSelectedRows().length > 0) {
                        ((DefaultTableModel) addingTable.getModel()).removeRow(addingTable.getSelectedRows()[0]);
                    }

                }

            }

        });
        saveButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    File file = new File(VariableNames.PATH_TO_BD);
                    InputStream in = new FileInputStream(file);
                    HSSFWorkbook wb = new HSSFWorkbook(in);
                    ExcelExtractor extractor = new ExcelExtractor(wb);
                    extractor.setFormulasNotResults(false); // Считать формулы
                    HSSFSheet sheet = wb.getSheet(tec.getShortName());
                    HSSFCellStyle style = wb.createCellStyle();
                    style.setBorderBottom(CellStyle.BORDER_THIN);
                    style.setBorderLeft(CellStyle.BORDER_THIN);
                    style.setBorderRight(CellStyle.BORDER_THIN);
                    style.setBorderTop(CellStyle.BORDER_THIN);

                    for (int i = 0; i < addingTable.getRowCount(); i++) {
                        HSSFRow row = MyUtils.getFirstEmptyRow(sheet);
                        HSSFCell cel1D = row.createCell(0);
                        Calendar dateCal = Calendar.getInstance();
                        dateCal.set(Integer.valueOf(addingTable.getValueAt(i, 0).toString().substring(6, 10)), Integer.valueOf(addingTable.getValueAt(i, 0).toString().substring(3, 5)) - 1, Integer.valueOf(addingTable.getValueAt(i, 0).toString().substring(0, 2)));
                        cel1D.setCellValue(dateCal.getTime());
                        CellStyle dateCellStyle = wb.createCellStyle();
                        dateCellStyle.setDataFormat(wb.createDataFormat().getFormat("dd.MM.yyyy"));
                        dateCellStyle.setBorderBottom(CellStyle.BORDER_THIN);
                        dateCellStyle.setBorderLeft(CellStyle.BORDER_THIN);
                        dateCellStyle.setBorderRight(CellStyle.BORDER_THIN);
                        dateCellStyle.setBorderTop(CellStyle.BORDER_THIN);
                        cel1D.setCellStyle(dateCellStyle);
                        for (int j = 2; j < Constants.NAEM_НEADER.length; j++) {
                            HSSFCell cel1 = row.createCell(j - 1);
                            if (j == 5 || j == 6 || j == 7 || j == 8 || j == 12 || j == 13 || j == 14 || j == 15 || j == 17 || j == 18 || j == 19) {
                                cel1.setCellType(Cell.CELL_TYPE_NUMERIC);
                                cel1.setCellValue(!(String.valueOf(addingTable.getValueAt(i, j))).isEmpty() ? Double.valueOf(addingTable.getValueAt(i, j).toString()) : new Double(0));

                            } else {
                                cel1.setCellValue(addingTable.getValueAt(i, j) != null ? addingTable.getValueAt(i, j).toString() : "");
                            }
                            cel1.setCellStyle(style);
                        }
                    }
                    FileOutputStream fileOut = new FileOutputStream(VariableNames.PATH_TO_BD);
                    wb.write(fileOut);
                    fileOut.close();
                    JOptionPane.showMessageDialog(null, "Изменение успешно сохранены", "Изменения сохранены", JOptionPane.OK_OPTION, new ImageIcon(ResourceManager.class.getResource("/images/success.png")));
                    MainDataBuilder.buildData();
                    Searcher.searchNaem();
                    Searcher.searchOur();
                    cleanTable();
                } catch (IOException e1) {
                    JOptionPane.showOptionDialog(null, "Нет доступа к базе данных. Она используется другой программой.\n Закройте все программы которые могут использовать ее (скорее всего это excel)", "данные не изменены", JOptionPane.OK_CANCEL_OPTION, JOptionPane.ERROR_MESSAGE, null, null, null);
                }
            }
        });

    }

    private void cleanTable() {
        model.setRowCount(0);
        saveButton.setEnabled(false);
    }

    private void setWidth(JTable table) {
        for (int i = 0; i < Constants.OUR_НEADER.length; i++) {
            int col = table.getColumnModel().getColumnIndex(Constants.OUR_НEADER[i]);
            TableColumn column = table.getColumnModel().getColumn(col);
            column.setPreferredWidth(80);
            column.setMinWidth(50);
        }

    }

    public ArrayList<OurTecInf> getTecInf() {
        return tecInf;
    }
}
